package com.scoresystem.web.controller.dispatcher;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.scoresystem.common.CommonValue;
import com.scoresystem.model.Student;
import com.scoresystem.model.Teacher;
import com.scoresystem.web.service.AdminService;
import com.scoresystem.web.ui.bridge.ViewBridgeImpl;
import com.scoresystem.web.ui.view.ViewFactory;

import net.sf.json.JSONObject;

public class AdminDispatcher extends BaseDispatcher implements IDispatcher {
	
	private AdminService service;
	public AdminDispatcher(){
		showable=null;
		viewbridge=new ViewBridgeImpl();
		service=new AdminService();
	}
	
	@Override
	public void dispatch(String option, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//添加学生
		if(option.equals(CommonValue.REQUEST_OP_INSERTSTU)){
			showable=ViewFactory.createShowInsertStuView();
			Student student=new Student();
			try{
				BeanUtils.populate(student, request.getParameterMap());
			}
			catch(Exception e){
				e.printStackTrace();
			}
			JSONObject json=service.checkoutInsertstu(student);
			viewbridge.setShowable(showable).showView(json, request, response);
		}
		//修改学生信息
		if(option.equals(CommonValue.REQUEST_OP_UPDATESTU)){
			showable=ViewFactory.createShowUpdateStuView();
			Student student=new Student();
			try{
				BeanUtils.populate(student, request.getParameterMap());
			}
			catch(Exception e){
				e.printStackTrace();
			}
			JSONObject json=service.checkoutUpdatestu(student);
			viewbridge.setShowable(showable).showView(json, request, response);
		}
		//查询学生
		if(option.equals(CommonValue.REQUEST_OP_QUERYSTU)){
			showable=ViewFactory.createShowStuQueryView();
			JSONObject json=service.checkoutquery
					(request.getParameter("major"), 
					request.getParameter("stuclass"));
			viewbridge.setShowable(showable).showView(json, request, response);
		}
		//增加教师并写入课程关系表
		if(option.equals(CommonValue.REQUEST_OP_INSERTTEA)){
			showable=ViewFactory.createShowInsertTeaView();
			Teacher teacher=new Teacher();
			try{
				BeanUtils.populate(teacher, request.getParameterMap());
			}
			catch(Exception e){
				e.printStackTrace();
			}
			JSONObject json=service.checkoutInsertTea
					(request.getParameterValues("subject"), teacher);
			viewbridge.setShowable(showable).showView(json, request, response);
		}
		if(option.equals(CommonValue.REQUEST_OP_DELETESTU)){
			showable=ViewFactory.createShowDelStuView();
			JSONObject json = service.checkoutDel(request.getParameterValues("stunums"));
			viewbridge.setShowable(showable).showView(json, request, response);
		}
	}

}
